package com.cy.springcloudalibaba.inits;

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.*;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Description: sentinel规则持久化（pull模式）
 * @ClassName: FileDataSourceInit
 * @Author: chenyu
 * @Date: 2025/1/20 10:53
 */
public class FileDataSourceInit implements InitFunc {

    private void mkdirIfNotExists(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private void createFileIfNotExists(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
    }
    @Override
    public void init() throws Exception {
        //指定规则文件位置
        String ruleDir = System.getProperty("user.name") + "/sentinel/rules";

        //流控规则
        String flowRulePath = ruleDir + "/flow-rule.json";
        //降级规则
        String degradeRulePath = ruleDir + "degrade-rule.json";
        //热点规则
        String paramFlowRulePath = ruleDir + "param-flow-rule.json";
        //系统规则
        String systemRulePath = ruleDir + "system-rule.json";
        //授权规则
        String authorityRulePath = ruleDir + "authority-rule.json";

        this.mkdirIfNotExists(ruleDir);

        this.createFileIfNotExists(flowRulePath);
        this.createFileIfNotExists(degradeRulePath);
        this.createFileIfNotExists(paramFlowRulePath);
        this.createFileIfNotExists(systemRulePath);
        this.createFileIfNotExists(authorityRulePath);

        //流控规则：可读数据源
        ReadableDataSource<String, List<FlowRule>> flowRuleRDS = new FileRefreshableDataSource<>(
                flowRulePath, flowRuleListParser
        );
        //将可读数据源注册至FlowRuleManager
        //这样当规则文件发生变化时，就会更新规则到内存
        FlowRuleManager.register2Property(flowRuleRDS.getProperty());

        //流控规则：可写数据源
        WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<>(
                flowRulePath, this::encodeJson
        );
        //将可写数据源注册至transport模块的writableDataSourceRegistry中
        //这样接收到控制台推送的规则时，Sentinel会先更新到内存，然后将规则写入到文件中
        WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);


        //降级规则：可读数据源
        ReadableDataSource<String, List<DegradeRule>> degradeRuleRDS = new FileRefreshableDataSource<>(
                flowRulePath, degradeRuleListParser
        );
        //将可读数据源注册至DegradeRuleManager
        //这样当规则文件发生变化时，就会更新规则到内存
        DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());

        //降级规则：可写数据源
        WritableDataSource<List<DegradeRule>> degradeRuleWDS = new FileWritableDataSource<>(
                degradeRulePath, this::encodeJson
        );
        //将可写数据源注册至transport模块的writableDataSourceRegistry中
        //这样接收到控制台推送的规则时，Sentinel会先更新到内存，然后将规则写入到文件中
        WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);

        //热点规则：可读数据源
        ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleRDS = new FileRefreshableDataSource<>(
                paramFlowRulePath, paramFlowRuleListParser
        );
        //将可读数据源注册至ParamFlowRuleManager
        //这样当规则文件发生变化时，就会更新规则到内存
        ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());

        //热点规则：可写数据源
        WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>(
                paramFlowRulePath, this::encodeJson
        );
        //将可写数据源注册至transport模块的writableDataSourceRegistry中
        //这样接收到控制台推送的规则时，Sentinel会先更新到内存，然后将规则写入到文件中
        ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);


        //系统规则：可读数据源
        ReadableDataSource<String, List<SystemRule>> systemRuleRDS = new FileRefreshableDataSource<>(
                systemRulePath, systemRuleListParser
        );
        //将可读数据源注册至ParamFlowRuleManager
        //这样当规则文件发生变化时，就会更新规则到内存
        SystemRuleManager.register2Property(systemRuleRDS.getProperty());

        //系统规则：可写数据源
        WritableDataSource<List<SystemRule>> systemRuleWDS = new FileWritableDataSource<>(
                systemRulePath, this::encodeJson
        );
        //将可写数据源注册至transport模块的writableDataSourceRegistry中
        //这样接收到控制台推送的规则时，Sentinel会先更新到内存，然后将规则写入到文件中
        WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);

        //授权规则：可读数据源
        ReadableDataSource<String, List<AuthorityRule>> authorityRuleRDS = new FileRefreshableDataSource<>(
                authorityRulePath, authorityRuleListParser
        );
        //将可读数据源注册至ParamFlowRuleManager
        //这样当规则文件发生变化时，就会更新规则到内存
        AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());

        //授权规则：可写数据源
        WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new FileWritableDataSource<>(
                authorityRulePath, this::encodeJson
        );
        //将可写数据源注册至transport模块的writableDataSourceRegistry中
        //这样接收到控制台推送的规则时，Sentinel会先更新到内存，然后将规则写入到文件中
        WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);

    }

    private final Converter<String, List<FlowRule>> flowRuleListParser = source -> JSON.parseObject(source,
            new TypeReference<List<FlowRule>>() {

            }

    );

    private final Converter<String, List<DegradeRule>> degradeRuleListParser = source -> JSON.parseObject(source,
            new TypeReference<List<DegradeRule>>() {

            }

    );

    private final Converter<String, List<ParamFlowRule>> paramFlowRuleListParser = source -> JSON.parseObject(source,
            new TypeReference<List<ParamFlowRule>>() {

            }

    );

    private final Converter<String, List<SystemRule>> systemRuleListParser = source -> JSON.parseObject(source,
            new TypeReference<List<SystemRule>>() {

            }

    );

    private final Converter<String, List<AuthorityRule>> authorityRuleListParser = source -> JSON.parseObject(source,
            new TypeReference<List<AuthorityRule>>() {

            }

    );

    private <T> String encodeJson(T t) {
        return JSON.toJSONString(t);
    }
}
